--
-- Author: yawei.zhu
-- Date: 2018-05-02 11:19:47
--
-- TaskController
--

local TaskView = import("..views.TaskView")
local DailyRewardView = import("..views.DailyRewardView")
local RoadHeroChallengeView = import("..views.RoadHeroChallengeView")
local RoadHeroNoticeView = import("..views.RoadHeroNoticeView")
local MainBranchTaskView = import("..views.MainBranchTaskView")
local MainBranchConfirmView = import("..views.MainBranchConfirmView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)


function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    self._model = app:getInst("TaskModel")
end

function ClassRef:removeListeners()
    self.super.removeListeners(self)
end

function ClassRef:onEvent(eventName, data)
    if eventName == "OnGameConnected" then
        -- TaskManager:C2S_GetDailyTaskInfoRequest()
    end
end

function ClassRef:listEvent()
    return {
        -- "OnGameConnected",
    }
end

function ClassRef:openView(data)
    self._model:initModel()

    if cc.isDead(self._view) then
        self._view = TaskView.new(app.mvc.VIEWTYPE_BLUR)
        self._view:onCloseView(handler(self, self.closeView))
        self._view:onClearView(handler(self, self.clearView))
        self._view:onOperate(handler(self, self.onOperate))
        self:addChild(self._view, data)
    end

    local menuData = self._model:getNewMenuList()
    self._view:refreshMenuList(menuData)
    self._view:show()

    -- 把经验条 提到 popUI的上一层
    app:sendMsg( "PlayerController", "showExpBar", SceneZOrder.popupUIZOrder + 1 ) 

    if data == nil then
        self._view:setTargetSelected(1) -- 默认选择主线任务
    else
        local menuData = self._model:getMenuDataByFuncId(data[1])
        if menuData == nil then
            self._view:setTargetSelected(1)
        else
            self._view:setTargetSelected(menuData.index, data[2])
        end

    end

    -- 添加TaskManager监听
    self:removeTaskListener()
    self._taskHandlers = {}
--    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("GET_DAILY_QUESTINFO_OK", function(event)
--        self._view:updateTaskProgress("daily")
--    end)
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("GET_WEEKLY_QUESTINFO_OK", function(event)
        self._view:updateTaskProgress("weekly")
    end)
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("REFRESH_TASK_OK", function(event) -- 支线和每日任务领奖成功返回

        if event.taskType == "daily" then
            self._view:onGetDailyTaskAward(event.taskId)
        elseif event.taskType == "weekly" then
            self._view:onGetWeeklyTaskAward(event.taskId)
        elseif event.taskType == "branch" then
            self._view:onGetBranchTaskAward(event.taskId)
        end
    end)

    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("GET_BOUNTY_INFO_OK", function(event)
        self._model:initBountyTasks()
        self._view:updateCircleTasks(self._model:getSelFameSubId())
    end)
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("GET_BOUNTY_TASK_OK", function(event)  -- 接取任务
        -- 默认追踪
        local newTaskId = self._model:getNewTaskId()
        if newTaskId then 
            TaskManager:saveTrackTask(newTaskId, newTaskId) 
        end

        self._view:updateCircleTasks(self._model:getSelFameSubId())
        self._model:setNewTaskId()
    end)
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("REFRESH_BOUNTY_TASK_OK", function(event) -- 赏金任务 刷新或者领奖(只播放特效)
        -- self._model:initBountyTasks()
        -- self._view:updateCircleTasks(self._model:getSelFameSubId())
        self._view:refreshCircleTask()

        -- 播放特效
        local refreshId, refreshIndex = self._model:getRefreshIndex()
        if refreshId and refreshIndex and refreshId == self._model:getSelFameSubId() then
            self._view:playRefreshAni(refreshIndex)
        end
        self._model:setRefreshIndex(nil)
    end)
    self._taskHandlers[#self._taskHandlers + 1] = TaskManager:addEventListener("REFRESH_DAILY_TASK_OK", function(event) -- 每日任务 刷新
        local _, refreshIndex = self._model:getRefreshIndex()

        --self._view:refreshDailyTask(refreshIndex)
        self._view:playDailyRefreshAni(refreshIndex)
        self._model:setRefreshIndex(nil)
    end)
end

function ClassRef:closeView(data)
    if self._view then
        self:removeChild(self._view, data)
    end

    -- 关闭界面时更新主界面任务红点
    if TaskManager:checkHasRewardByTaskType() then
        UD.badge:setNum(Constant.FUNC_TYPE_TASK, 1)
    else
        UD.badge:setNum(Constant.FUNC_TYPE_TASK, 0)
    end
end

-- 显示每日任务奖励预览UI
function ClassRef:showDailyReward(isLock, boxIndex, questType, itemLists)
    local view = DailyRewardView.new()
    view:onCloseView(function()
        UIHandler:removePopupUiByKey(view:getViewName())
    end)
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
    view:showData(isLock, boxIndex, questType, itemLists)
end

function ClassRef:clearView()
    self:removeTaskListener()
    
    if self._view then
        self._view = nil
    end

    app:sendMsg( "PlayerController", "showExpBar" )
end

function ClassRef:removeTaskListener()
    if self._taskHandlers then
        for i,v in ipairs(self._taskHandlers) do
            TaskManager:removeEventListener(v)
        end
        self._taskHandlers = {}
    end
end

function ClassRef:closeSelf()
    UIHandler:handleMessage({id = Constant.FUNC_TYPE_TASK, mode = "close"})
end

-- 打开英雄之路挑战界面
function ClassRef:openHeroView(box, level, step)
    local view = RoadHeroChallengeView.new()
    view:onCloseView(function(sender)
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()

    if box then
        view:showBox(level, self._model:getRoadOfHeroProcess() )
    else
        view:showChallenge(level, step, self._model:getRoadOfHeroProcess() )
    end
end

-- 更新英雄之路界面
function ClassRef:updateRoadHeroInfo(process)
    if not self:isViewAlive() then return end
    self._view:updateRoadHeroInfo(process)
end


function ClassRef:updateNewTasks(tasks)
    if not tasks then return end 

    -- 更新主界面任务红点（为了效率，此处只更新完成的，领奖的会在任务界面关闭的时候统一更新）
    if UD.badge:getNum(Constant.FUNC_TYPE_TASK) <= 0 then
        for _, task in pairs(tasks) do
            if (task:isBounty() or task:isWeekly()) and task:isFinished() then
                UD.badge:setNum(Constant.FUNC_TYPE_TASK, 1)
                break
            end
        end
    end

    if not self._view then return end
    self._view:updateNewTasks(tasks)
end


-- 检查是否有英雄之路解锁
function ClassRef:checkHasNewRoadOfHero(oldLevel, newLevel)
    -- 检查是否在野外地图
    local mapData = GD:queryMapById(MapManager:getMapId())
    if mapData and Enums.mapType[tonumber(mapData.maptype)] ~= "normal" then
        return
    end
    local configs = GD:getHeroRoads()
    for _, data in ipairs(configs) do
        local openLevel = tonumber(data.level)
        if openLevel > oldLevel and openLevel <= newLevel then

            -- 插入英雄之路tips
            local params = {
                remindId = Constant.FUNC_TYPE_TASK_ROADHERO,
                dataTemp = {layer = tonumber(data.layer), index = tonumber(data.order)}
            }
            UIHandler:getDesktopController():insertFourthTips( params )

            break
        end
    end
end

function ClassRef:showHeroRoadNoticeView(data)
    local view = RoadHeroNoticeView.new()
    view:onCloseView(function(sender)
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()

    view:updateView(data)

    display.nodeRemoveForNotHit(view._ui.Panel, function()
        view:closeView()
    end)
end


function ClassRef:showBranchTaskDialog(data)
    local view = MainBranchTaskView.new(app.mvc.VIEWTYPE_BLUR)
    view:onCloseView(function(sender)
        UIHandler:removeSystemUiByKey(sender:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addSystemUi(view, view:getViewName())
    view:show()

    view:updateView(data)
    self._branchTaskView = view
end

function ClassRef:closeBranchTaskDialog()
    if not cc.isDead(self._branchTaskView) then
        UIHandler:removeSystemUiByKey(self._branchTaskView:getViewName())
    end
    self._branchTaskView = nil
end

function ClassRef:showBranchConfirmDialog(data)
    local view = MainBranchConfirmView.new()
    view:onCloseView(function(sender)
        UIHandler:removePopupUiByKey(sender:getViewName())
    end)
    view:onOperate(handler(self, self.onOperate))
    UIHandler:addPopupUi(view, view:getViewName())
    view:show()
    view:updateView(data)
end

-------------------------------------------------------


-------------------------------------------------------
function ClassRef:onOperate(op, data)
--    print("TaskController:onOperate op = " .. op)
    if op == "selectedTarget" or op == "selectedSubTarget" then
        self._view:showTaskView(op, data)


    elseif op == "GET_TASK_REWARD" then
        TaskManager:C2S_GetTaskRewardRequest(data.taskType, data.taskId)
    elseif op == "GET_DAILY_INFO" then
        TaskManager:C2S_GetDailyTaskInfoRequest()
    elseif op == "GET_WEEKLY_INFO" then
        TaskManager:C2S_GetWeeklyTaskInfoRequest()
    elseif op == "GET_BOUNTY_TASK_INFO" then
        TaskManager:C2S_GetBountyTaskInfoRequest()
    elseif op == "GET_BOUNTY_TASK" then
        TaskManager:C2S_GetBountyTaskRequest(data.taskId)
    elseif op == "REFRESH_BOUNTY_TASK" then
        TaskManager:C2S_RefreshBountyTaskRequest(data.taskId) 
    elseif op == "refreshDailyTask" then
        self._model:setRefreshIndex(data:getPos())
        TaskManager:C2S_RefreshDailyTaskRequest(data:getId())   
    elseif op == "TASK_AUTO_WAY" then
        EM:notify("onTrackingWay",{trackNpcId = data.findNpcId, trackTaskId = data.trackTaskId, isTracking = true, findCall = function(isFinding)
            if isFinding then
                self:closeSelf()
            end
        end})
    elseif op == "OPEN_REWARD" then
        local itemList = self._model:getDailyTaskRewards( data.needProgress, data.nowProgress )
        self:showDailyReward(data.lock, data.boxIndex, data.questType, itemList)
    elseif op == "OPEN_WEEKLY_REWARD" then
        --TODO 传boxIndex进去
        local itemList = self._model:getWeeklyTaskRewards( data.needProgress, data.nowProgress )
        self:showDailyReward(data.lock, data.needProgress, data.questType, itemList)
    elseif op == "TASK_TO_LIST" then
        local taskId = tostring(data.taskId)
        local add = data.add
        TaskManager:saveTrackTask(taskId, add and taskId or "0") 
    elseif op == "BRANCH_TASK_TO_LIST" then
        local taskId = tostring(data.taskId)
        local add = data.add

        -- 把之前追踪的支线任务清掉
        if add then
            -- 先刷新ui展示
            self._view:updateBranchTrackTask(data.taskId)

            local branchTasks = self._model:getBranchTasks()
            for _, task in ipairs(branchTasks) do
                if TaskManager:isNeedTrack(task:getId()) then
                    if task:getId() ~= data.taskId then
                        TaskManager:saveTrackTask(tostring(task:getId()), "0") 
                    end
                end
            end
        end

        TaskManager:saveTrackTask(taskId, add and taskId or "0") 
    elseif op == "reqRoadOfHeroProcess" then
        self._model:reqRoadOfHeroProcess()
    elseif op == "openHeroBox" then
        self:openHeroView(true, data)
    elseif op == "openHeroNode" then
        self:openHeroView(false, data[1], data[2])
    elseif op == "reqChallenge" then
        local direction = FieldManager:getCharacterDirection()
        local dir = "left"
        if direction == Enums.FaceTo.left then dir = "right" end
        -- 此处传过去的方向好像是反的
        BattleManager:roadOfHeroBattleStart({id = data, dir = dir}) 
    elseif op == "reqRoadOfHeroOpenBox" then
        self._model:reqRoadOfHeroOpenBox(data)
    elseif op == "openRoadOfHero" then
        UIHandler:handleMessage({id=Constant.FUNC_TYPE_TASK_ROADHERO, mode="open"})
    elseif op == "confimSelectBranchTask" then
        self:showBranchConfirmDialog(data)
    elseif op == "reqSelectBranchTask" then
        TaskManager:reqSelectMainTask(data.curTaskId, data.nextTaskId)
    else
        -- 其余的都是调用_model里面的方法 

        -- if op == "getMainTaskData" then
        --     return self._model:getMainTaskData()
        -- elseif op == "splitTaskDigests" then
        --     return self._model:splitTaskDigests()
        -- elseif op == "getDailyTasks" then
        --     return self._model:getDailyTasks()
        -- elseif op == "getFinishedDailyTaskNumber" then
        --     return self._model:getFinishedDailyTaskNumber()
        -- elseif op == "getTotalDailyTaskNumber" then
        --     return self._model:getTotalDailyTaskNumber()
        -- elseif op == "getDailyTaskRewardProgress" then
        --     return self._model:getDailyTaskRewardProgress(data)
        -- elseif op == "getMenuDataByFuncId" then
        --     return self._model:getMenuDataByFuncId(data)
        -- elseif op == "getBountyTaskInfo" then
        --     return self._model.getBountyTaskInfo()
        -- elseif op == "getBountyTaskProgressBySubkey" then
        --     return self._model:getBountyTaskProgressBySubkey(data)
        -- elseif op == "getFameSubKeyById" then
        --     return self._model:getFameSubKeyById(data)
        -- elseif op == "setSelFameSubId" then
        --     return self._model:setSelFameSubId(data)
        -- elseif op == "getSelFameSubId" then
        --     return self._model:getSelFameSubId()
        -- elseif op == "getBountyTasks" then
        --     return self._model:getBountyTasks()
        -- elseif op == "isBountyTaskFinished" then
        --     return self._model:isBountyTaskFinished()
        -- elseif op == "isNeedTrack" then
        --     return self._model:isNeedTrack(data)
        -- elseif op == "getBountyTaskFameBySubkey" then
        --     return self._model:getBountyTaskFameBySubkey(data)
        -- elseif op == "setRefreshIndex" then
        --     return self._model:setRefreshIndex(data)
        -- elseif op == "getBountyTaskRefresh" then
        --     return self._model:getBountyTaskRefresh(data[1], data[2])
        -- end

        
        if self._model[op] ~= nil then
            if data and type(data) == "table" then
                return self._model[op](self._model, data[1], data[2]) -- 如果有多个参数，就直接在后面添加
            else
                return self._model[op](self._model, data)
            end
        end

    end

    
end

return ClassRef
